package cn.jinjimi.app.main.fragment;

import android.app.Activity;
import android.content.Context;
import android.webkit.WebSettings;
import android.webkit.WebView;

import cn.jinjimi.app.R;
import cn.jinjimi.app.webview.WebViewJavascriptBridge;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.webview.WebViewHelper;
import cn.jinjimi.framework.router.Router;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.widget.MyWebView;

import static cn.jinjimi.app.webview.WebViewHelper.getUserAgent;

/**
 *
 * @author lforxeverc
 * @date 2017/5/12
 */

public class IdeaFragment extends BaseFragment {
    private WebViewJavascriptBridge handler;
    private MyWebView mWebview;
    private String mUrl;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_reader_idea;
    }

    @Override
    protected void initial() {
        mWebview = (MyWebView) findView().findViewById(R.id.wv);
        setUpWebView(getActivity(), mWebview);
        handler = new WebViewJavascriptBridge(mWebview);
        handler.enableJavascriptInterface(true);
        mUrl = getArguments().getString(BundleKey.URL);
        mWebview.loadUrl(mUrl);

    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 设置webview
     */
    public void setUpWebView(final Context context, WebView webView) {
        webView.setVerticalScrollBarEnabled(true);
        webView.setHorizontalScrollBarEnabled(false);
        // 自适应屏幕
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setJavaScriptEnabled(true);

        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAllowContentAccess(true);

        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setDatabaseEnabled(true);

        webView.getSettings().setUserAgentString(webView.getSettings().getUserAgentString() + getUserAgent(context));
        webView.getSettings().setUseWideViewPort(true);
        webView.setWebViewClient(new IdeaWebViewClient(getActivity()));

    }

    private class IdeaWebViewClient extends WebViewHelper.WebViewClient {
        public IdeaWebViewClient(Activity activity) {
            super(activity);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            super.shouldOverrideUrlLoading(view, url);
            Router.create(IdeaFragment.this.getActivity(), url).open();
            return true;
        }
    }

}
